package cn.yujiago.activiti.service.impl;

import cn.yujiago.activiti.constant.BillConstant;
import cn.yujiago.activiti.constant.MessageConstant;
import cn.yujiago.activiti.dto.FinanceBillVO;
import cn.yujiago.activiti.dto.ResponseEntity;
import cn.yujiago.activiti.entity.FinanceBill;
import cn.yujiago.activiti.entity.User;
import cn.yujiago.activiti.mapper.FinanceBillMapper;
import cn.yujiago.activiti.service.SQJFLCService;
import cn.yujiago.activiti.util.CommonUtils;
import cn.yujiago.activiti.util.SessionUtils;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("sqjflcService")
public class SQJFLCServiceImpl extends WorkflowServiceImpl<FinanceBillVO> implements SQJFLCService {

    @Resource
    private FinanceBillMapper financeBillMapper;

    @Override
    public ResponseEntity startProcessInstance(FinanceBillVO financeBillVO) {
        User user = SessionUtils.get();

        // 将数据保存到数据库，并取得ID，作为businessKey，用于将流程实例与业务关联起来
        financeBillVO.setUser(user);
        financeBillVO.setId(CommonUtils.getUUID());
        financeBillMapper.insert(financeBillVO);

        // 设置认证用户的id
        this.getIdentityService().setAuthenticatedUserId(user.getUsername());
        // 流程变量
        HashMap<String, Object> variables = new HashMap<>();
        variables.put("applyUser", user.getUsername());
        variables.put("content", financeBillVO.getContent());
        variables.put("money", financeBillVO.getMoney());

        // 根据流程定义key启动流程实例，并关联业务
        String businessKey = financeBillVO.getId().toString();
        ProcessInstance instance = this.getRuntimeService().startProcessInstanceByKey(financeBillVO.getKey(), businessKey, variables);

        return ResponseEntity.build(200, MessageConstant.OPT_SUCCESS);
    }

    @Override
    public ResponseEntity auditByTaskId(String taskId) {

        //根据任务id，获取申请单id，从而获取请假单信息
        String businessKey = this.findBusinessKeyByTaskId(taskId);

        // 通过id查询业务单实体
        FinanceBill financeBill = financeBillMapper.selectById(businessKey);

        //根据任务id获取流程定义实体对象，从而获取当前任务完成之后的连线名称
        List<String> outcomeList = this.findOutComeListByTaskId(taskId);

        //根据任务id查询所有历史审批信息，帮助当前审批人完成审批
        List<Comment> commentList = this.findCommentByTaskId(taskId);

        Map<String, Object> map = new HashMap<>();

        map.put("taskId", taskId);
        map.put("financeBill", financeBill);
        map.put("outcomeList", outcomeList);
        map.put("commentList", commentList);

        return ResponseEntity.build(200, MessageConstant.QUERY_SUCCESS, map);
    }

    @Override
    public ResponseEntity saveSubmitTask(FinanceBillVO financeBillVO) {
        // 任务id
        String taskId = financeBillVO.getTaskId();
        // 批注信息
        String comment = financeBillVO.getComment();
        // 请假单id
        String id = financeBillVO.getId();
        // 获取流程实例id
        Task task = this.getTaskService().createTaskQuery().taskId(taskId).singleResult();
        String processInstanceId = task.getProcessInstanceId();
        // 设置审批人
        this.getIdentityService().setAuthenticatedUserId(SessionUtils.get().getUsername());
        // 添加批注信息
        this.getTaskService().addComment(taskId, processInstanceId, comment);
        Map<String, Object> variables = new HashMap<>();
        // 完成任务，设置变量
//		variables.put("President", "王中军");
//		variables.put("VP", "副总裁");
//		variables.put("PM", "范冰冰经纪人");

        variables.put("msg", financeBillVO.getMsg());

        this.getTaskService().complete(taskId, variables);

        // 指定下一个任务的办理人

        // 判断流程是否结束
        ProcessInstance pi = this.getRuntimeService().createProcessInstanceQuery()
                .processInstanceId(processInstanceId)// 使用流程实例ID查询
                .singleResult();
        if (null == pi) {
            // 更新单状态
            FinanceBill financeBill = new FinanceBill();
            financeBill.setId(financeBillVO.getId());
            financeBill.setStatus(BillConstant.AUDIT_COMPLETE);
            financeBillMapper.updateFinanceBillStatus(financeBill);
        }

        return ResponseEntity.build(200, MessageConstant.OPT_SUCCESS);
    }

    @Override
    public ResponseEntity detailByPIIdAndFBId(String processInstanceId, String financeBillId) {
        // 获取批注信息
        List<Comment> commentList = this.getTaskService().getProcessInstanceComments(processInstanceId);
        // 通过id查询业务单实体
        FinanceBill financeBill = financeBillMapper.selectById(financeBillId);
        Map<String, Object> map = new HashMap<>();

        map.put("commentList", commentList);
        map.put("financeBill", financeBill);

        return ResponseEntity.build(200, MessageConstant.QUERY_SUCCESS, map);
    }
}
